package com.block.product.service.union;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.IUnionLoginService;
import com.market.member.service.IMemberSourceInfoService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class HuaRongUnionLoginService implements IUnionLoginService {

    private static final Logger log = LogFactory.getProductUniLog();

    @Autowired
    private IMemberSourceInfoService memberSourceInfoService;
    @Autowired
    private MemberSourceInfoMapper memberSourceInfoMapper;

    @Override
    public UnionLoginResult checkUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam) throws Exception {
        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getCheckUrl();
        String mobile = uniLoginDTO.getMobile();
        String mobileMd5 = SecureUtil.md5(mobile);
        String apiSecret = apiInfoParam.getApiSecret();
        String apiKey = apiInfoParam.getApiKey();
        MemberSourceInfo memberSourceInfo =memberSourceInfoMapper.selectByMobileMd5(mobileMd5);


        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("mobile", mobile);

        bizmMap.put("realname", memberSourceInfo.getRealname());
        bizmMap.put("idcardno", memberSourceInfo.getIdcard());

        String  bizData = new AES(Mode.CBC, Padding.PKCS5Padding, apiSecret.getBytes(), apiKey.getBytes()).encryptBase64(JSON.toJSONString(bizmMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestNo", RandomUtil.randomString(32));
        paramMap.put("channelCode", apiInfoParam.getApiCode());
        paramMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        paramMap.put("tranData", bizData);


        log.info("【花融钱包】撞库开始【queryUrl】{}【paramMap】{}", checkUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl).header("Content-Type", "application/json").body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【花融钱包】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("respCode");
        String msg = resultObject.getString("respMsg");
        JSONObject data = resultObject.getJSONObject("data");
        Boolean success = resultObject.getBoolean("success");
        String status = data.getString("status");

        String jsonString = JSONObject.toJSONString(data);
        loginResult.setCode(respCode);
        loginResult.setMessage(msg);
        loginResult.setResultInfo(jsonString);
        loginResult.setParamInfo(JSON.toJSONString(paramMap));

        if (StrUtil.equals(respCode, "200") &&  StrUtil.equals(status, "000")) {
            loginResult.setSuccess(success);
        }
        return loginResult;
    }

    @Override
    public UnionLoginResult loginUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam,String resultInfo) throws Exception {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getLoginUrl();
        String apiSecret = apiInfoParam.getApiSecret();
        String apiKey = apiInfoParam.getApiKey();
        JSONObject jsonObject = JSONObject.parseObject(resultInfo);
        String orderNo = jsonObject.getString("orderNo");

        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("orderNo", orderNo);

        String  bizData = new AES(Mode.CBC, Padding.PKCS5Padding, apiSecret.getBytes(), apiKey.getBytes()).encryptBase64(JSON.toJSONString(bizmMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestNo", RandomUtil.randomString(32));
        paramMap.put("channelCode", apiInfoParam.getApiCode());
        paramMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        paramMap.put("tranData", bizData);

        log.info("【花融钱包】联登开始【queryUrl】{}【paramMap】{}", checkUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl).header("Content-Type", "application/json").body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【花融钱包】联登结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("respCode");
        String msg = resultObject.getString("respMsg");
        JSONObject data = resultObject.getJSONObject("data");
        String status = data.getString("status");

        loginResult.setCode(respCode);
        loginResult.setMessage(msg);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(paramMap));
        if (StrUtil.equals(respCode, "200") &&  StrUtil.equals(status, "000")) {
            String url = data.getString("unionLoginUrl");
            loginResult.setLoginUrl(url);
            loginResult.setSuccess(true);
        }
        return loginResult;
    }


}
